package com.test2;

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v111.log.Log;

import java.util.HashMap;
import java.util.Map;

public class Testlog {

    public static void main(String[] args) {
        String path = "C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe";
        if(args.length > 0){
            path = args[0];
        }
        get("http://www.hao123.com/",path);
    }

    public static Map<String, String> get(String url,String path) {
        // 参数配置
        System.setProperty("webdriver.chrome.driver", path);

        ChromeOptions option = new ChromeOptions();
//        option.addArguments("headless"); // 无界面参数
//        option.addArguments("no-sandbox"); // 禁用沙盒
        // 通过ChromeOptions的setExperimentalOption方法，传下面两个参数来禁止掉谷歌受自动化控制的信息栏
        //option.setExperimentalOptions("useAutomationExtension", false);
        //option.setExperimentalOptions("excludeSwitches", Collections.singletonList("enable-automation"));


        //设置为 headless 模式 （必须）
        //option.addArguments("--headless");
        option.addArguments("--disable-gpu");//谷歌文档提到需要加上这个属性来规避bug
        option.addArguments("--no-sandbox");// “–no - sandbox”参数是让Chrome在root权限下跑
        option.addArguments("--disable-dev-shm-usage");
        option.addArguments("lang=zh_CN.UTF-8");
        //option.addArguments("window-size=1920x1080"); //指定浏览器分辨率

        ChromeDriver driver = new ChromeDriver(option);
        String title = "";
        String num = "";
        String img = "";

        // 创建EventFiringWebDriver 实例
        // Register the Listener with the event firing driver

        DevTools devTools = driver.getDevTools();



        devTools.createSession();


        driver.get("http://www.baidu.com");
        Map<String,Object> parameters = new HashMap<>();
        parameters.put("url","http://www.soso.com");
        driver.executeCdpCommand("Page.navigate",parameters);
//        try{
//            driver.executeCdpCommand("Browser.close",parameters);
//        }catch (Exception e){
//            e.printStackTrace();
//        }

        devTools.getDomains().javascript().addBindingCalledListener(s->{
            System.out.println(s);
        });
        devTools.send(Log.enable());
        devTools.addListener(Log.entryAdded(),
                logEntry -> {
                    System.out.println("log: "+logEntry.getText());
                    System.out.println("level: "+logEntry.getLevel());
                });

// Check the terminal output for the browser console messages.
        try {
            Thread.sleep(100000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

